import Vue from "vue"

export default{
    namespaced: true,
    state:()=>({
        goodList:[],
    }),
    getters:{
         setAllChecked(state){
             let AllCkecked=true;//全选按钮
             let TotalPrice=0;//总价
             let yChoice=0;//以选择
             let number=0;//商品数量
             state.goodList.forEach(v=>{
                 //全选
                 if(!v.ischecked){(AllCkecked=false)}
                 //总价 已选择的数量
                 if(v.ischecked){TotalPrice+=v.price*v.num;yChoice+=v.num}
                 number+=v.num
             })
             //判断所有商品删除后全选按钮的状态
             if(state.goodList.length===0){
                 AllCkecked=false
             }
             return{
                 number,
                 yChoice,
                 TotalPrice,
                 AllCkecked
             };
        }
    },
    mutations:{
        //首页添加商品到购物车
        goodAdd(state,obj){
            let {goodList}=state
            for(var i=0;i<goodList.length;i++){
                if(goodList[i].stock_id==obj.stock_id){
                    goodList[i].num++
                    return
                }
            }
            Vue.set(obj,"num",1)
            Vue.set(obj,'ischecked',true)
            state.goodList.push(obj)
        },

        //详情页添加商品到购物车
        DetailAdd(state,item){
            console.log(item)
                let {obj,shopNumber}=item
            let {goodList}=state
            for(var i=0;i<goodList.length;i++){
                if(goodList[i].stock_id==obj.stock_id){
                    goodList[i].num+=shopNumber;
                    return
                }
            }
            Vue.set(obj,"num",shopNumber)
            Vue.set(obj,'ischecked',true)
            state.goodList.push(obj)
        },

        //单选按钮
        checked(state,index){
            state.goodList[index].ischecked=!state.goodList[index].ischecked
        },
        //全选按钮
        setAllChecked(state,Bool) {
            state.goodList.forEach(v=>{
                    v.ischecked=!Bool
            })
        },
        //增减数量按钮
        setNum(state,obj){
            let {index,num}=obj
            if((state.goodList[index].num+num)>0){
                state.goodList[index].num+=num
                return
            }
        },
        //选择全部删除
        removShop(state){
            let arr=[];
            for(var i=0;i<state.goodList.length;i++){
                if(!state.goodList[i].ischecked){
                    arr.push(state.goodList[i])
                }
            }
            state.goodList=arr;
        },
        //点击按钮删除
        setShop(state,index){
            state.goodList.splice(index,1)
        }
    }
}